﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using eWallet.Security.Cryptography;
using eWallet.Data.Local;

namespace eWallet
{
	/// <summary>
	/// Interaction logic for CryptoModuleCreatorWindow.xaml
	/// </summary>
	public partial class CryptoModuleCreatorWindow : Window
	{
		public CryptoModuleCreatorWindow()
		{
			InitializeComponent();
		}



		public bool CacheCredentials
		{
			get { return this.CacheCredentialsCheckbox.IsChecked.HasValue && this.CacheCredentialsCheckbox.IsChecked.Value; }
			set { this.CacheCredentialsCheckbox.IsChecked = value; }
		}

		public eWalletDataSet.GroupsRow EncryptionGroup { get; set; }

		public ICryptoModule SelectedModule { get; private set; }


		protected override void OnRender(DrawingContext drawingContext)
		{
			if (null == this.EncryptionGroup)
			{
				throw new NullReferenceException("EncryptionGroup property cannot be null.");
			}

			string grp = this.EncryptionGroup.Name;
			if (!this.EncryptionGroup.IsDescriptionNull() && !string.IsNullOrEmpty(this.EncryptionGroup.Description))
				grp = grp + string.Format(" ({0})", this.EncryptionGroup.Description);

			this.PasswordInfoText.Text = string.Format(this.PasswordInfoText.Tag.ToString(), grp);

			switch (this.EncryptionGroup.EncryptionMethod)
			{
				case EncryptionMethod.Password:
					this.PasswordGroup.Visibility = Visibility.Visible;
					this.PasswordTextbox.Focus();
					break;

				default:
					throw new NotSupportedException("The specified encryption method is not supported.");
			}

			base.OnRender(drawingContext);
		}

		private void OKButton_Click(object sender, RoutedEventArgs e)
		{
			switch (this.EncryptionGroup.EncryptionMethod)
			{
				case EncryptionMethod.Password:
					if (string.IsNullOrEmpty(this.PasswordTextbox.Password) || this.PasswordTextbox.Password.Trim().Length == 0)
					{
						MessageBox.Show(this, "The password must not be empty.", "Empty Password", MessageBoxButton.OK, MessageBoxImage.Error);
						return;
					}

					this.SelectedModule = new PasswordCryptoModule(this.PasswordTextbox.Password);
					break;

				default:
					throw new NotSupportedException("The specified encryption method is not supported.");
			}

			this.DialogResult = true;
			this.Close();
		}

		private void CancelButton_Click(object sender, RoutedEventArgs e)
		{
			this.DialogResult = false;
			this.Close();
		}

	}

}
